package cn.zyy.hotel.service.impl;

import cn.zyy.hotel.dao.*;
import cn.zyy.hotel.entity.*;
import cn.zyy.hotel.service.CheckoutService;
import cn.zyy.hotel.utils.UUIDUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

@Service
@Transactional
public class CheckoutServiceImpl implements CheckoutService {

    @Resource
    private CheckoutMapper checkoutMapper;

    @Resource
    private CheckinMapper checkinMapper;

    @Resource
    private OrdersMapper ordersMapper;

    @Resource
    private RoomTypeMapper roomTypeMapper;

    @Resource
    private RoomMapper roomMapper;

    //添加退房记录
    @Transactional(rollbackFor = RuntimeException.class)
    public int addCheckout(Checkout checkout) {
        Checkin checkin = checkinMapper.selectById(checkout.getCheckInId());
        //添加退房记录  设置创建时间
        checkout.setCreateDate(new Date());
        checkout.setCheckOutNumber(UUIDUtils.randomUUID());
        checkout.setConsumePrice(checkin.getPayPrice());
        //调用添加退房记录方法
        int line = checkoutMapper.addCheckout(checkout);
        if (line > 0) {
            //修改入住表中的状态  为 2 - 已离店
            checkin.setStatus(2);
            //调用修改入住订单的方法
            checkinMapper.updateCheckin(checkin);
            //修改订单表中的状态  修改成 4 - 已完成
            Orders orders = new Orders();
            orders.setStatus(4);
            orders.setId(checkin.getOrdersId());
            //调用修改订单的方法
            ordersMapper.updateOrders(orders);
            //修改房型表中可用的房间数，已入住的房间数  已预订数
            RoomType roomType = roomTypeMapper.selectById(checkin.getRoomTypeId());
            roomType.setAvilableNum(roomType.getAvilableNum()+1);
            roomType.setLivedNum(roomType.getLivedNum()-1);
            //调用修改房型的方法
            roomTypeMapper.updateRoomType(roomType);
            //修改房间状态
            Room room = new Room();
            room.setId(checkin.getRoomId());
            room.setStatus(3);
            roomMapper.updateRoom(room);
        }
        return line;
    }



}
